import java.util.Properties;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class MainTest {

	@SuppressWarnings("static-access")
	private static final void overrideCommandLineProperty(String[] args)
			throws InterruptedException {

		Options os = new Options();

		// java -D<name>=<value>
		os.addOption(OptionBuilder
				.withArgName("property=value")
				.hasArgs(2)
				.withValueSeparator()
				.withDescription(
						"search the objects which have the target property and value")
				.create("D"));

		CommandLineParser clp = new GnuParser();

		Properties sysp = System.getProperties();

		try {
			CommandLine cmd = clp.parse(os, args);
			Properties p = cmd.getOptionProperties("D");

			System.out.println("property keys:"+p.keySet());
			for (Entry<Object, Object> ok : p.entrySet()) {
				String key = String.valueOf(ok.getKey());
				String value = String.valueOf(ok.getValue());

				if (sysp.containsKey(key)) {
					throw new RuntimeException(
							"property config exist in system property:" + key);
				} else {
					sysp.put(key, value);
					System.out.println("put property:" + key + "=" + value);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

	/**
	 * <pre>
	 * steps:
	 * 1.download dependency jar commons-cli-1.2.jar in 
	 * http://repo1.maven.org/maven2/commons-cli/commons-cli/1.2/commons-cli-1.2.jar
	 * ---\MainTest.java
	 * ---\lib\
	 * ------\commons-cli-1.2.jar
	 * 
	 * 
	 * 2.javac -Djava.ext.dirs=..\lib MainTest.java
	 * 3.java -Djava.ext.dirs=..\lib MainTest -Dcity=beijing,wuhang -Dsite=58,ganji
	 * </pre>
	 * 
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		System.out.println();
		System.out.println("parse command line params ...");
		overrideCommandLineProperty(args);
		System.out.println("parse command line params over...");

	}
}
